package com.uroad.liaoningpos.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boc.aidl.printer.AidlPrinter;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.ums.AppHelper;
import com.uroad.liaoningpos.R;
import com.uroad.liaoningpos.common.BaseActivity;
import com.uroad.liaoningpos.common.SPContants;
import com.uroad.liaoningpos.dialog.PayDetailDialog;
import com.uroad.liaoningpos.model.PayDetailMDL;
import com.uroad.liaoningpos.util.BitmapUtil;
import com.uroad.liaoningpos.util.SPUtils;
import com.uroad.liaoningpos.webService.PosWS;
import com.uroad.lib.adapter.rv.CommonAdapter;
import com.uroad.lib.adapter.rv.ViewHolder;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.data.DateTimeUtil;
import com.uroad.lib.util.file.SDUtil;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.string.StringUtils;
import com.uroad.lib.widget.dialog.DialogHelper;
import com.uroad.lib.widget.loadmore.LoadMoreRecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @创建者 wlw
 * @创建时间 2019/4/2 18:30
 * @描述 余额查询
 */
public class OrderQueryActivity extends BaseActivity implements OnDateSetListener {
    private static String TAG = "OrderQueryActivity";
    @BindView(R.id.tvStartTime)
    TextView             tvStartTime;
    @BindView(R.id.tvEndTime)
    TextView             tvEndTime;
    @BindView(R.id.tvPagerCount)
    TextView             tvPagerCount;
    @BindView(R.id.rvPayDetails)
    LoadMoreRecyclerView rvPayDetails;
    @BindView(R.id.srlRefresh)
    SwipeRefreshLayout srlRefresh;

    private CommonAdapter<PayDetailMDL> adapter;
    private List<PayDetailMDL>          list;
    private PayDetailDialog detailDialog;
    private TimePickerDialog            timePickerDialog;
    private boolean                     isShowTimeDialog = false;
    private SimpleDateFormat sfym = new SimpleDateFormat("yyyy-MM-dd");
    private int selectTime;
    private Date startDate;
    private Date endDate;
    private String startTime;
    private String endTime;
    private int pageindex = 1;
    private int pagesize = 10;
    private String posimei;
    private AidlPrinter printerModule;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_pay_detail);
        ButterKnife.bind(this);
        setTitle("订单查询");
        initData();
        initDialog();
        initListener();
        bindDeviceService();
    }

    private void initListener() {
        rvPayDetails.setLoadMoreListener(new LoadMoreRecyclerView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                pageindex++;
                loadData();
            }
        });
        srlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageindex = 1;
                loadData();
            }
        });
    }
    @Override
    protected void bindDeviceServiceSuccess() {
        super.bindDeviceServiceSuccess();
        try {
            printerModule = AidlPrinter.Stub.asInterface(deviceService.getPrinter());
            detailDialog.setPrintModule(printerModule);
        } catch (RemoteException e) {
            e.printStackTrace();
            LogUtil.i(TAG, "获取打印模块异常");
        }
    }

    private void initData() {
        list = new ArrayList<>();
        posimei = (String) SPUtils.get(this, SPContants.SP_IMEI, "");
        adapter = new CommonAdapter<PayDetailMDL>(this, R.layout.item_pay_detail, list) {
            @Override
            protected void convert(ViewHolder holder, final PayDetailMDL payDetailMDL, int position) {
                if ("1".equalsIgnoreCase(payDetailMDL.getType())) {
                    holder.setText(R.id.tvPayType, "刷卡");
                    holder.setBackgroundDrawable(R.id.tvPayType, getResources().getDrawable(R.drawable.bg_roundretangle_red_shape));
                } else if ("2".equalsIgnoreCase(payDetailMDL.getType())) {
                    holder.setText(R.id.tvPayType, "银联付款码");
                    holder.setBackgroundDrawable(R.id.tvPayType, getResources().getDrawable(R.drawable.bg_roundretangle_blue_shape));
                } else if ("3".equalsIgnoreCase(payDetailMDL.getType())) {
                    holder.setText(R.id.tvPayType, "高速付款码");
                    holder.setBackgroundDrawable(R.id.tvPayType, getResources().getDrawable(R.drawable.bg_roundretangle_green_shape));
                } else if ("4".equalsIgnoreCase(payDetailMDL.getType())) {
                    holder.setText(R.id.tvPayType, "微信付款码");
                    holder.setBackgroundDrawable(R.id.tvPayType, getResources().getDrawable(R.drawable.bg_roundretangle_green_shape));
                } else if ("5".equalsIgnoreCase(payDetailMDL.getType())) {
                    holder.setText(R.id.tvPayType, "支付宝付款码");
                    holder.setBackgroundDrawable(R.id.tvPayType, getResources().getDrawable(R.drawable.bg_roundretangle_blue_shape));
                }
                holder.setText(R.id.tvPayTime, payDetailMDL.getDate() + " " + payDetailMDL.getTime());
                holder.setText(R.id.tvPayNo, "流水号："+payDetailMDL.getOrderno());
                holder.setText(R.id.tvAmount, StringUtils.divideHundred(payDetailMDL.getAmt()));
                holder.setOnClickListener(R.id.llLayoutContent, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        detailDialog.setData(payDetailMDL);
                        detailDialog.show();
//                        showPayDetail();
                    }
                });
            }
        };
        rvPayDetails.setAdapter(adapter);
        rvPayDetails.setCanLoadMore(false);
//        Date selectDate = new Date();
//        String date = sfym.format(selectDate);
//        tvStartTime.setText(date);
//        tvEndTime.setText(date);
    }

    @OnClick({R.id.tvStartTime,R.id.tvEndTime})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvStartTime:
                selectTime = 1;
                showTimePickerDialog();
                break;
            case R.id.tvEndTime:
                selectTime = 2;
                showTimePickerDialog();
                break;
        }
    }

    private void initDialog() {
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        timePickerDialog = new TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("请选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis() - tenYears)
                .setMaxMillseconds(System.currentTimeMillis())
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.main_title_blue))
                .setType(Type.YEAR_MONTH_DAY)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.darkgray))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.main_title_blue))
                .setWheelItemTextSize(14)
                .build();
        timePickerDialog.setCancelable(false);

        detailDialog = new PayDetailDialog(this);
    }

    protected void showTimePickerDialog(){
        if (isShowTimeDialog) {
            return;
        }
        isShowTimeDialog = true;
        timePickerDialog.show(getSupportFragmentManager(),
                "year_month_day");
    }


    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        isShowTimeDialog = false;
        Date selectDate = new Date(millseconds);
        String date = sfym.format(selectDate);

        if (selectTime == 1) {
            tvStartTime.setText(date);
            startDate = selectDate;
            startTime = date;
            if (endDate == null) {
                return;
            }
            int resule = DateTimeUtil.compareDate(startDate, endDate);
            if (resule > 0) {
                //开始时间>结束时间
                endDate = startDate;
                endTime = startTime;
                tvEndTime.setText(date);
            }
        } else if (selectTime == 2) {
            tvEndTime.setText(date);
            endDate = selectDate;
            endTime = date;
            if (startDate == null) {
                return;
            }
            int resule = DateTimeUtil.compareDate(startDate, endDate);
            if (resule > 0) {
                //开始时间>结束时间
                startDate = endDate;
                startTime = endTime;
                tvStartTime.setText(date);
            }
        }

        loadData();
    }

    private void loadData() {
        DialogHelper.showLoading(this, "正在查询");
        doRequest(PosWS.paylist, PosWS.paylistParams(
                pageindex + "", pagesize + "", startTime, endTime,posimei));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        DialogHelper.endLoading();
        if (0 == resultCode) {
            showShortToast("打印成功");
        } else if (-1 == resultCode) {
            showShortToast("打印失败:"+data.getStringExtra("resultCode"));
            Log.d("LOG", data.getStringExtra("resultCode") + "");//具体的code见ServiceResult
        }
    }

    @Override
    public void onCancel() {
        isShowTimeDialog = false;
    }

    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        DialogHelper.endLoading();
        srlRefresh.setRefreshing(false);
        JSONObject jsonObject = JSON.parseObject(result);
        if (FastJsonUtils.getJsonStatu00(jsonObject)) {
            JSONObject data = jsonObject.getJSONObject("data");
            if (data != null) {
                List<PayDetailMDL> payDetailMDLS = FastJsonUtils.parseArrayJSON(data.getString("paylist"), PayDetailMDL.class);
                if (payDetailMDLS != null) {
                    if (pageindex == 1) {
                        list.clear();
                    }
                    list.addAll(payDetailMDLS);
                    if (payDetailMDLS.size() < pagesize) {
                        rvPayDetails.setCanLoadMore(false);
                    } else {
                        rvPayDetails.setCanLoadMore(true);
                    }
                    adapter.notifyDataSetChanged();
                    rvPayDetails.notifyDataSetChanged();
                } else {
                    showShortToast("获取数据失败，请稍后重试");
                }
            } else {
                showShortToast("获取数据失败，请稍后重试");
            }
        }else{
            showShortToast(FastJsonUtils.getErrMsg00(jsonObject));
        }
    }

    @Override
    public void OnHttpNetWork(String msg) {
        super.OnHttpNetWork(msg);
        DialogHelper.endLoading();
        srlRefresh.setRefreshing(false);
    }

    @Override
    public void OnHttpFailure(String msg) {
        super.OnHttpFailure(msg);
        DialogHelper.endLoading();
        srlRefresh.setRefreshing(false);
    }
}
